package com.nvn.washiodriver.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.nvn.washiodriver.R;
import com.nvn.washiodriver.adapters.MenuListAdapter;
import com.nvn.washiodriver.network.WebServiceCommunicatorListener;
import com.nvn.washiodriver.network.ws.BaseWSControl;
import com.nvn.washiodriver.network.ws.BaseWSControl.WebServiceFlag;
import com.nvn.washiodriver.network.ws.CheckInWSControl;
import com.nvn.washiodriver.network.ws.CheckOutWSControl;
import com.nvn.washiodriver.services.UpdateLocationService;
import com.nvn.washiodriver.utils.SessionManager;
import com.nvn.washiodriver.utils.Statics;
import com.parse.ParseObject;
import com.parse.ParseUser;

public class MainActivity extends Activity implements
		WebServiceCommunicatorListener, OnClickListener {

//	public static String APP_ID = "b6bce03a92304cbab5964755fd07c98a";
	private String[] mMenuIcons, mMenuTexts;
	private ListView mListView;
	private MenuListAdapter mAdapter;
	private CountDownTimer cDT;
	private boolean ready = false;
	private ProgressDialog pd;
	private TextView mTvCheck;
	private ToggleButton mTgbCheck;
	private boolean isStartUpdateLocationService = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		overridePendingTransition(R.anim.slide_in_from_left, R.anim.anim_alpha);

		initView();
		initProperties();
		initListeners();
		ParseUser.getCurrentUser().fetchInBackground(null);
		
		ParseObject cityObject = ParseUser.getCurrentUser().getParseObject("location_city");
		if(null != cityObject){
			Statics.cityId = cityObject.getObjectId();
		}else{
			Statics.cityId = "4gmticz6Tz";
		}
		
		startUpdateLocationService();
		
//		checkForUpdates();
	}

	private void initView() {
		mMenuIcons = getResources().getStringArray(R.array.menu_icons);
		mMenuTexts = getResources().getStringArray(R.array.menu_texts);
		mListView = (ListView) findViewById(R.id.list_menus);
		mAdapter = new MenuListAdapter(this, mMenuIcons, mMenuTexts,
				R.layout.item_list_menu);
		mListView.setAdapter(mAdapter);

		cDT = new CountDownTimer(3000, 3000) {

			@Override
			public void onTick(long arg0) {
			}

			@Override
			public void onFinish() {
				ready = false;
			}
		};

		mTvCheck = (TextView) findViewById(R.id.tv_menu_check);
		mTgbCheck = (ToggleButton) findViewById(R.id.tgb_menu_check);

	}

	private void initProperties() {
		pd = new ProgressDialog(this);
		pd.setCancelable(false);
	}

	private void initListeners() {
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				if (pos < 3 && !Statics.isNetworkConnected(getBaseContext())) {
					new AlertDialog.Builder(MainActivity.this)
							.setTitle("Notice")
							.setMessage("Oops! No internet connection.")
							.setPositiveButton("Ok",
									new DialogInterface.OnClickListener() {

										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {

										}
									}).show();
				} else {
					goToDetailPage(pos);
				}
			}
		});

		mTgbCheck.setOnClickListener(this);
	}

	private void goToDetailPage(int pos) {
		Intent i = null;
		String userObjectId = ParseUser.getCurrentUser().getObjectId();
		if (userObjectId != null) {
			switch (pos) {
			case 0: // My Orders
				i = new Intent(this, OrderActivity.class);
				i.putExtra("TITLE", mMenuTexts[pos]);
				break;

			case 1: // My Schedule
				i = new Intent(this, ScheduleActivity.class);
				i.putExtra("TITLE", mMenuTexts[pos]);
				break;

			case 2: // Account
				i = new Intent(this, MyAccountActivity.class);
				i.putExtra("TITLE", mMenuTexts[pos]);
				break;

			case 3: // Settings
				i = new Intent(this, SettingsActivity.class);
				i.putExtra("TITLE", mMenuTexts[pos]);
				break;

			case 4:
				i = new Intent(Intent.ACTION_CALL);
				i.setData(Uri.parse("tel:" + Statics.WASHIO_PHONE));
				break;

			case 5:
				i = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:"
						+ Statics.WASHIO_PHONE));
				break;

			}
		} else {
			i = new Intent(this, LoginActivity.class);
			i.putExtra("TITLE", "Login");
		}

		if (i != null) {
			startActivity(i);
		}
	}

	@Override
	public void onBackPressed() {
		if (ready) {
			super.onBackPressed();
		} else {
			ready = true;
			Statics.showToast(this, "Press back again to exit");
			cDT.start();
		}
	}

	@Override
	protected void onDestroy() {
		SessionManager.destroySession();
		stopUpdateLocationService();
		super.onDestroy();
	}

	@Override
	public void onConnectionOpen(BaseWSControl wsControl, WebServiceFlag flag) {
		if (!pd.isShowing()) {
			pd.setMessage("Loading...");
			pd.show();
		}
	}

	@Override
	public void onConnectionError(BaseWSControl wsControl, WebServiceFlag flag,
			String error) {
		if (flag == WebServiceFlag.CHECK_IN) {
			mTvCheck.setText(R.string.txt_check_out);
			mTgbCheck.setChecked(false);
		}

		if (flag == WebServiceFlag.CHECK_OUT) {
			mTvCheck.setText(R.string.txt_check_in);
			mTgbCheck.setChecked(true);
		}
		Statics.showToast(this, error);
		pd.dismiss();
	}

	@Override
	public void onConnectionDone(BaseWSControl wsControl, WebServiceFlag flag,
			Object result) {
		pd.dismiss();

		if (flag == WebServiceFlag.CHECK_IN) {
			Statics.showToast(this, result.toString());
			mTvCheck.setText(R.string.txt_check_in);
		}

		if (flag == WebServiceFlag.CHECK_OUT) {
			Statics.showToast(this, result.toString());
			mTvCheck.setText(R.string.txt_check_out);
		}

	}

	@Override
	public void onUpdateData(BaseWSControl wsControl, WebServiceFlag flag,
			Object data) {
	}

	@Override
	public void onClick(View v) {
		if (mTgbCheck.isChecked()) {
			new CheckInWSControl(this, this, ParseUser.getCurrentUser()
					.getObjectId()).execute();
		} else {
			new CheckOutWSControl(this, this, ParseUser.getCurrentUser()
					.getObjectId()).execute();
		}
	}

	public void startUpdateLocationService() {
		Intent intent = new Intent(this, UpdateLocationService.class);
		startService(intent);
		isStartUpdateLocationService = true;
	}

	public void stopUpdateLocationService() {
		if (isStartUpdateLocationService) {
			Intent intent = new Intent(this, UpdateLocationService.class);
			stopService(intent);
			isStartUpdateLocationService = false;
		}
	}
	
//	private void checkForCrashes() {
//		CrashManager.register(this, APP_ID, new CrashManagerListener() {
//			public void onCrashesSent() {
//				runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						Toast.makeText(MainActivity.this,
//								"Crash data was sent. Thanks!",
//								Toast.LENGTH_SHORT).show();
//					}
//				});
//			}
//		});
//	}
//
//	private void checkForUpdates() {
//		// Remove this for store builds!
//		UpdateManager.register(this, APP_ID);
//	}
//
//	@Override
//	protected void onResume() {
//		checkForCrashes();
//		super.onResume();
//	}
}
